package com.fan.gofast.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;


/**
 * http请求连接封装，支持SSL HEAD HTTP HTTPS
 * httpclient封装类
 */
@Slf4j
public class HttpClient {



    // utf-8字符编码
    public static final String CHARSET_UTF_8 = "utf-8";

    // HTTP内容类型。
    public static final String CONTENT_TYPE_TEXT_XML = "text/xml";

    // HTTP内容类型。相当于form表单的形式，提交数据
    public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";

    // HTTP内容类型。相当于form表单的形式，json数据提交
    public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";

    // 连接管理器
    private static PoolingHttpClientConnectionManager pool;

    // 请求配置
    private static RequestConfig requestConfig;
    private static HttpClientBuilder httpBuilder = null;
    private static CloseableHttpClient client = null;
    private static volatile boolean isRunning;

    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            // 配置同时支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
            // 初始化连接管理器
            pool = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            // pool max connect
            pool.setMaxTotal(1000);
            // 设置最大路由
            pool.setDefaultMaxPerRoute(500);
            int socketTimeout = 20000;
            int connectTimeout = 2000;
            int connectionRequestTimeout = 2000;
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();

            httpBuilder = HttpClients.custom();
            httpBuilder.setConnectionManager(pool);
            httpBuilder.setKeepAliveStrategy((response, context) -> 20 * 1000);
            httpBuilder.evictExpiredConnections();
            client = httpBuilder.build();
            isRunning = true;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }


    private static void setParam(HttpEntityEnclosingRequestBase http, String params, String charset, String contentType) {
        try {
            // 设置参数
            if (params != null && params.trim().length() > 0) {
                StringEntity stringEntity = new StringEntity(params, charset == null ? CHARSET_UTF_8 : charset);
                stringEntity.setContentType(contentType == null ? CONTENT_TYPE_FORM_URL : contentType);
                http.setEntity(stringEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送 post请求
     *
     * @param httpUrl url
     * @param params  参数(格式:key1=value1&key2=value2)
     */
    public static String sendHttpPost(String httpUrl, String params, String contentType, String headerToken) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        setParam(httpPost, params, null, contentType);
        return sendHttp(httpPost, null, headerToken);
    }


    /**
     * 发送 post请求
     *
     * @param httpUrl url
     * @param params  参数(格式:key1=value1&key2=value2)
     */
    public static String sendHttpPost(String httpUrl, String params, String contentType) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        setParam(httpPost, params, null, contentType);
        return sendHttp(httpPost, null);
    }

    public static String sendHttpPostWithHeader(String httpUrl, String params, String contentType, Map<String, String> headerMap) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        headerMap.forEach((key, value) -> {
            httpPost.setHeader(key, value);
        });
        setParam(httpPost, params, null, contentType);
        return sendHttpNew(httpPost, null);
    }

    public static String sendHttpGetWithHeader(String httpUrl, Map<String, Object> params, Map<String, String> headerMap) {
        String parem = convertStringParamter(params);
        HttpGet httpGet = new HttpGet(httpUrl + "?" + parem);
        headerMap.forEach((key, value) -> {
            httpGet.setHeader(key, value);
        });
        return sendHttpNew(httpGet, null);
    }

    /**
     * 发送 post请求
     *
     * @param httpUrl url
     * @param params  参数(格式:key1=value1&key2=value2)
     */
    public static String sendHttpPost(String httpUrl, String params) {
        return sendHttpPostWithContentType(httpUrl, params, null, null);
    }

    /**
     * 发送 post请求
     *
     * @param httpUrl url
     * @param params  参数(格式:key1=value1&key2=value2)
     */
    public static String sendHttpPostWithContentType(String httpUrl, String params, String charset, String contentType) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        setParam(httpPost, params, charset, contentType);
        return sendHttp(httpPost, charset);
    }

    /**
     * 发送 post请求
     *
     * @param httpUrl
     */
    public static String sendHttpPost(String httpUrl) {
        return sendHttp(new HttpPost(httpUrl), null);
    }

    /**
     * 发送 get请求
     *
     * @param httpUrl
     */
    public static String sendHttpGet(String httpUrl) {
        return sendHttp(new HttpGet(httpUrl), null);
    }


    /**
     * 发送 get请求
     *
     * @param httpUrl
     */
    public static String sendHttpGet(String httpUrl, String userAgent, String referer) {
        HttpGet get = new HttpGet(httpUrl);
        if (userAgent != null) {
            get.setHeader("User-Agent", userAgent); // 设
        }
        if (referer != null) {
            get.setHeader("Referer", referer);
        }
        return sendHttp(get, null);
    }

    /**
     * 发送 post请求（带文件）
     *
     * @param httpUrl   地址
     * @param maps      参数
     * @param fileLists 附件
     */
    public static String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        if (maps != null) {
            for (String key : maps.keySet()) {
                meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
            }
        }
        if (fileLists != null) {
            for (File file : fileLists) {
                FileBody fileBody = new FileBody(file);
                meBuilder.addPart("files", fileBody);
            }
        }
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return sendHttp(httpPost, null);
    }

    /**
     * 发送 post请求（带文件、带请求头head）
     *
     * @param httpUrl
     * @param headerMap 请求头
     * @param maps      参数
     * @return
     */
    public static String sendHttpPostWithHeader(String httpUrl, Map<String, String> headerMap, Map<String, String> maps, File file) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        headerMap.forEach((key, value) -> {
            httpPost.setHeader(key, value);
        });
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        if (maps != null) {
            for (String key : maps.keySet()) {
                meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
            }
        }
        FileBody fileBody = new FileBody(file);
        meBuilder.addPart("file", fileBody);
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return sendHttp(httpPost, null);
    }

    /**
     * 发送 post请求
     *
     * @param maps 参数hashmap
     */
    public static String sendHttpPost(String httpUrl, Map<String, Object> maps, String headToken) {
        String param = convertStringParamter(maps);
        return sendHttpPost(httpUrl, param, null, headToken);
    }

    /**
     * 发送 post请求
     *
     * @param maps 参数hashmap
     */
    public static String sendHttpPost(String httpUrl, Map<String, Object> maps) {
        String param = convertStringParamter(maps);
        return sendHttpPost(httpUrl, param);
    }

    /**
     * 发送 post请求 发送json数据
     *
     * @param httpUrl    地址
     * @param paramsJson 参数(格式 json)
     */
    public static String sendHttpPostJson(String httpUrl, String paramsJson) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        setParam(httpPost, paramsJson, "UTF-8", CONTENT_TYPE_JSON_URL);
        return sendHttp(httpPost, null);
    }

    /**
     * 发送 post请求 发送json数据
     *
     * @param httpUrl    地址
     * @param paramsJson 参数(格式 json)
     */
    public static String sendHttpPostJson(String httpUrl, String paramsJson, String headerToken) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        setParam(httpPost, paramsJson, "UTF-8", CONTENT_TYPE_JSON_URL);
        return sendHttp(httpPost, null, headerToken);
    }

    /**
     * 发送 post请求 发送xml数据
     *
     * @param httpUrl   地址
     * @param paramsXml 参数(格式 Xml)
     */
    public static String sendHttpPostXml(String httpUrl, String paramsXml, String charset) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        setParam(httpPost, paramsXml, charset, CONTENT_TYPE_TEXT_XML);
        return sendHttp(httpPost, charset);
    }

    /**
     * 发送 post请求
     *
     * @param maps 参数hashmap
     */
    public static String sendHttpGet(String httpUrl, Map<String, Object> maps) {
        String parem = convertStringParamter(maps);
        return sendHttpGet(httpUrl, parem);

    }

    private static String sendHttpGet(String httpUrl, String params) {
        HttpGet httpGet = new HttpGet(httpUrl + "?" + params);
        return sendHttp(httpGet, null);
    }

    /**
     * 将map集合的键值对转化成：key1=value1&key2=value2 的形式
     *
     * @param parameterMap 需要转化的键值对集合
     * @return 字符串
     */
    @SuppressWarnings("rawtypes")
    public static String convertStringParamter(Map parameterMap) {
        StringBuffer parameterBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator iterator = parameterMap.keySet().iterator();
            String key, value;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                if (parameterMap.get(key) != null) {
                    value = parameterMap.get(key).toString();
                } else {
                    value = "";
                }
                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }
        return parameterBuffer.toString();
    }

    private static CloseableHttpClient getHttpClient() {

		/*CloseableHttpClient httpClient = HttpClients.custom()
				// 设置连接池管理
				.setConnectionManager(pool)
				// 设置请求配置
				.setDefaultRequestConfig(requestConfig)
				// 设置重试次数
				.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build();*/

        return client;
    }

    /**
     * 发送请求
     *
     * @param httpPostOrGet
     * @return
     */
    private static String sendHttp(HttpRequestBase httpPostOrGet, String charset) {
        return sendHttp(httpPostOrGet, charset, null);
    }


    /**
     * 发送请求
     *
     * @param httpPostOrGet
     * @return
     */
    private static String sendHttp(HttpRequestBase httpPostOrGet, String charset, String headerToken) {
        if (charset == null) {
            charset = CHARSET_UTF_8;
        }
        CloseableHttpResponse response = null;
        // 响应内容
        String responseContent = null;
        // 响应实例
        HttpEntity entity = null;
        try {
            CloseableHttpClient httpClient = getHttpClient();
            // 创建默认的httpClient实例.
            if(headerToken != null){
                httpPostOrGet.setHeader("token", headerToken);
            }
            // 配置请求信息
            httpPostOrGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPostOrGet);
            // 得到响应实例
            entity = response.getEntity();

            // 可以获得响应头
            // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
            // for (Header header : headers) {
            // System.out.println(header.getName());
            // }

            // 得到响应类型
            // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());

            // 判断响应状态
            if (response.getStatusLine().getStatusCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()
                        + "; response message:" + EntityUtils.toString(entity, charset));
            }

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                responseContent = EntityUtils.toString(entity, charset);
            }

        } catch (Exception e) {
            log.info("======sendHttp返回{}", ExceptionUtil.getMsg(e));
            throw new RuntimeException("异常",e);
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * get获取图片流
     *
     * @param httpUrl httpUrl
     * @return byte[]
     * @author leijian
     * @date 2019/9/18 11:54
     */
    public static byte[] getHttpImgByte(String httpUrl) throws Exception {
        HttpRequestBase httpPostOrGet = new HttpGet(httpUrl);
        CloseableHttpClient httpClient;
        CloseableHttpResponse response = null;
        // 响应内容
        byte[] buffer = null;
        // 响应实例
        HttpEntity entity = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = getHttpClient();
            // 配置请求信息
            httpPostOrGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPostOrGet);
            entity = response.getEntity();
            // 获得响应头
            Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
            if (Arrays.stream(headers).anyMatch(x -> x.getValue() != null && x.getValue().contains("image") || x.getValue().contains("pdf"))) {
                // 响应头包含image,得到文件流
                buffer = EntityUtils.toByteArray(entity);
            } else {
                // 响应头不包含image，不是想要的结果
                throw new Exception("HTTP Request image is not success, Response code is " + response.getStatusLine().getStatusCode()
                        + "; request url : " + httpUrl + "; response message:" + EntityUtils.toString(entity, CHARSET_UTF_8));
            }
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }



    public static HttpEntity getHttpByte(String httpUrl) throws Exception {
        HttpRequestBase httpPostOrGet = new HttpGet(httpUrl);
        CloseableHttpClient httpClient;
        // 创建默认的httpClient实例.
        httpClient = getHttpClient();
        // 配置请求信息
        httpPostOrGet.setConfig(requestConfig);
        // 执行请求
        return httpClient.execute(httpPostOrGet).getEntity();
    }

    /**
     * 发送请求（去掉默认token）
     *
     * @param httpPostOrGet
     * @return
     */
    private static String sendHttpNew(HttpRequestBase httpPostOrGet, String charset) {
        if (charset == null) {
            charset = CHARSET_UTF_8;
        }
        CloseableHttpClient httpClient;
        CloseableHttpResponse response = null;
        // 响应内容
        String responseContent = null;
        // 响应实例
        HttpEntity entity = null;
        try {
            // 创建默认的httpClient实例.
            httpClient = getHttpClient();
            // 配置请求信息
            httpPostOrGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPostOrGet);
            // 得到响应实例
            entity = response.getEntity();

            // 可以获得响应头
            // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
            // for (Header header : headers) {
            // System.out.println(header.getName());
            // }

            // 得到响应类型
            // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());

            // 判断响应状态
            if (response.getStatusLine().getStatusCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()
                        + "; response message:" + EntityUtils.toString(entity, charset));
            }

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                responseContent = EntityUtils.toString(entity, charset);
            }

        } catch (Exception e) {
            // e.printStackTrace();
            log.error("HttpClient.sendHttpNew请求异常：",e);
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    public static void shutdown() {
        if (Objects.nonNull(pool) && isRunning) {
            isRunning = false;
            pool.shutdown();
            try {
                client.close();
            } catch (IOException e) {
            }
        }
    }
}
